package arraySort;

import java.util.Arrays;

/**
 * provides methods to insert an element in a sorted array.
 * 
 * @author Jakob Karolus, Kevin Munk
 * @version 1.0
 * 
 */
public class ArraySort {

	/**
	 * inserts a number into a sorted array of numbers.
	 * 
	 * @param element
	 *            the element to insert.
	 * @param array
	 *            the sorted array.
	 * @return the sorted array with the element at the right position.
	 */
	public static int[] insertElement(int element, int[] array) {
		// Copies the array and increases the length of the new array
		int[] tempArray = Arrays.copyOf(array, array.length + 1);
		// Insert the element at the last position of the new array
		tempArray[tempArray.length - 1] = element;
		// Sort the array
		Arrays.sort(tempArray);

		return tempArray;
	}

	/**
	 * inserts a number into a sorted array of numbers.
	 * 
	 * @param element
	 *            the element to insert.
	 * @param array
	 *            the sorted array.
	 * @return the sorted array with the element at the right position.
	 */
	public static int[] insertElementFast(int element, int[] array) {
		// throw new UnsupportedOperationException("Implement me!");
		int[] tempArray = new int[array.length + 1];
		for (int i = 0; i < tempArray.length; i++) {
			if (i < array.length && element > array[i]) {
				tempArray[i] = array[i];
			} else {
				tempArray[i] = element;
				System.arraycopy(array, i, tempArray, i + 1, array.length - i);
				break;
			}
		}
		return tempArray;
	}
}
